<script setup>

import axios from "axios";
import {ServerHost} from "@/main.ts";
import {ElNotification} from "element-plus";
import {onMounted, ref, toRaw} from "vue";
import {downloadImg} from "@/utils";
import dayjs from "dayjs";

const policyNum = ref(4)
const policyList = ref([])
const policyNList = ref([])
const hotPolicyList = ref([])
const isLoadingList = ref(true)

const loadList = async () => {
  console.log("开始获取政策列表")
  await axios.get(`${ServerHost}/getPolicyList?key=`)
      .then((res) => {
        if (res.status === 200) {
          ElNotification({
            title: '政策获取成功',
            type: 'success',
            position: 'bottom-right',
          })
          policyList.value = res.data;
          // 随机选取n条政策
          if (policyList.value.length < policyNum.value) {
            policyNList.value = policyList.value
          } else {
            // 深拷贝policyListCopy，防止子组件修改父组件数据
            const policyListCopy = structuredClone(toRaw(policyList.value))
            policyNList.value = []
            for (let i = 0; i < policyNum.value; i++) {
              //policy4List
              const randomIndex = Math.floor(Math.random() * policyListCopy.length)
              policyNList.value.push(policyListCopy[randomIndex])
              policyListCopy.splice(randomIndex, 1)
            }
            console.log(policyList.value)

          }
          // 下载封面
          policyNList.value.forEach((policy, i) => {
            downloadImg(policyNList.value[i].coverImg, "PolicyCover/")
                .then(res => {
                  if (res.status === 200) {
                    const type = 'image/png'
                    const blob = new Blob([res.data], {type: type})
                    const imgFile = new File([blob], policyNList.value[i].coverImg, {type: type})
                    policyNList.value[i].coverImgUrl = URL.createObjectURL(imgFile)
                  }
                })
          })
          // hasLoad.value = true
          isLoadingList.value = false
        } else {
          ElNotification({
            title: '政策获取失败',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })
  await axios.get(`${ServerHost}/getPolicyList?orderBy=pageview`)
     .then((res) => {
        if (res.status === 200) {
          hotPolicyList.value = res.data;
        }
     })
}

// 懒加载政策列表
const observerDiv = ref(null)
const hasLoad = ref(false)
onMounted(() => {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        if (!hasLoad.value) {
          loadList()
        }
      }
    });
  });
  observer.observe(observerDiv.value);
})


</script>

<template>
  <div ref="observerDiv"/>
  <div class="m-container m-4 items-center">
    <!--  4宫格推送  -->
    <el-card v-for="policy in policyNList" class="top-item" :body-style="{padding: 0, height: '100%', width: '100%'}">
      <router-link :to="'/Policy/' + policy.id" target="_blank">
        <img class="good-item-img" :src="policy.coverImgUrl" alt="image">
        <p class="goods-item-name">{{ policy.title }}</p>
      </router-link>
    </el-card>

    <!--  热点政策  -->
    <el-card class="hot-policy">
      <p class="hot-policy-title mb-2">热点政策</p>
      <el-link class="hot-policy-item mb-1" v-for="(policy, index) in hotPolicyList">
        <router-link :to="'/Policy/' + policy.id" target="_blank">
          <el-text class="hot-policy-p" truncated> {{ `${index + 1}`.padStart(2, '0') }} {{ policy.title }}</el-text>
        </router-link>
      </el-link>
    </el-card>

    <!--  最新政策  -->
    <el-card class="policy-list">
      <p class="hot-policy-title mb-2">最新政策</p>
      <div class="mt-2 mb-2" v-for="policy in policyList">
        <router-link :to="'/Policy/' + policy.id" target="_blank">
          <p>{{ policy.title }} <span class="policy-data">{{ dayjs(policy.postTime).format('YY/MM/DD HH:mm') }}</span></p>
        </router-link>
      </div>
    </el-card>
  </div>


</template>

<style scoped lang="scss">
.m-container {
  //background: #8e9dbf;
  display: grid;
  grid-template-columns: repeat(3, 300px);
  grid-template-rows: repeat(2, 200px);
  grid-gap: 10px;
  place-self: center;
}

.top-item {
  width: 100%;
  height: 100%;
  position: relative;
  padding: 0;
}

.good-item-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-item-name {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  padding: 4px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  word-break: keep-all;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.hot-policy {
  height: 100%;
  min-height: 0;
  grid-row-start: 1;
  grid-row-end: 3;
  grid-column-start: 3;
  grid-column-end: 3;
}

.hot-policy-title {
  font-family: "思源宋体 Heavy", serif;
  font-size: 1.1rem;
  color: var(--el-color-primary);
}

.hot-policy-p {
  width: 260px;
}

.policy-list {
  grid-column-start: 1;
  grid-column-end: 4;
}

.policy-data{
  font-size: 0.8rem;
  color: var(--el-color-info);
}

</style>
